from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from .forms import RegisterForm
from utils.json_fun import to_json_data
from utils.res_code import Code
from .models import Users


# Create your views here.
class RegisterView(View):
    def get(self,request):
        return render(request, "users/register.html")

    def post(self, request):
        # 1.校验参数（form实现）
        form = RegisterForm(request.POST)
        if form.is_valid():
            # 2.创建数据
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            mobile = form.cleaned_data.get("mobile")
            Users.objects.create_user(username=username, password=password, mobile=mobile)  # 密码不能是明文不能直接用create
            return to_json_data(errmsg='恭喜您，注册成功！')
        else:
            # 将表单的报错信息进行拼接
            err_msg_list = []
            for item in form.errors.values():
                err_msg_list.append(item[0])
            err_msg_str = '/'.join(err_msg_list)
            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)


class LoginView(View):
    def get(self,request):
        return render(request, "users/login.html")


